const mongoose = require('mongoose');
const Cate = require('../models/cate.model');

exports.create = function(req, res, next) {
    console.log(req.body);
    var cate = new Cate(req.body);

    cate.save().then(data => {
        res.json(data);
    })
}

exports.update = function(req, res, next) {
    const id = req.params.id;
    // console.log(id);

    Cate.findByIdAndUpdate(id, { $set: req.body }).then(data => {
        res.json(data);
    });
}

exports.remove = function(req, res, next) {
    var id = req.params.id;
    var ids = [];
    Cate.findOne({ _id: id }, function(err, doc) {
        ids = [doc._id];
        doc.getChildren().then(function(docs) {
            for (var i = 0; i < docs.length; i++) {
                ids.push(docs[i]._id);
            }
            Cate.remove({ _id: { $in: ids } }).then(data => {
                res.json({ 'message': 'delete ok' });
            })
        });
    });
};


function reverseTree(data, pid) {
    var result = [],
        temp;
    var data = JSON.parse(JSON.stringify(data));

    for (var i in data) {
        if (data[i].parentId == pid) {
            result.push(data[i]);

            data[i].title = data[i].text;
            delete data[i].text;

            temp = reverseTree(data, data[i]._id);
            // console.log(temp);
            if (temp.length > 0) {
                data[i].children = temp;
            }
        }
    }
    return result;

}
exports.list = function(req, res, next) {
    var type = req.params.type || 1;
    Cate.find({ type: type }, function(err, data) {
        var rpTree = reverseTree(data, null);
        res.json(rpTree);
    });
}
exports.get = function(req, res, next) {
    const id = req.params.id;
    Cate.findById(id).then(data => {
        res.json(data);
    })
}